package com.example.blog.controller;

import com.example.blog.constants.Constants;
import com.example.blog.model.BlogInfo;
import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.service.BlogInfoService;
import com.example.blog.service.UserInfoService;
import com.example.blog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 博客相关操作
 */
@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogInfoController {
    @Autowired
    private BlogInfoService blogInfoService;

    @Autowired
    private UserInfoService userInfoService;
    /**
     * 获取博客列表
     * @return
     */
    @RequestMapping("/getBlogList")
    public List<BlogInfo> getBlogList() {

        List<BlogInfo> blogs = blogInfoService.getBlogList();
        //对detail做长度限制（提取摘要）
        for(BlogInfo blog : blogs) {
            String content = blog.getContent();
            String precis = content.substring(0, Math.min(200, content.length())) + "...";
            blog.setContent(precis);
        }
        return blogs;
    }

    @RequestMapping("/getBlogListByUserName")
    public List<BlogInfo> getBlogListByName(String userName) {
        UserInfo user = userInfoService.getUserByName(userName);
        List<BlogInfo> blogs = blogInfoService.getBlogListByUserId(user.getId());
        //对detail做长度限制（提取摘要）
        for(BlogInfo blog : blogs) {
            String content = blog.getContent();
            String precis = content.substring(0, Math.min(200, content.length())) + "...";
            blog.setContent(precis);
        }
        return blogs;
    }

    /**
     * 获取博客详情
     * @param blogId
     * @param request
     * @return
     */
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request) {
        BlogInfo result = blogInfoService.getBlogById(blogId);

        //获取用户id 判断 当前登录用户是否为该文章作者,方便判断是否有对该文章的修改权限
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId = JwtUtils.getIdInToken(token);
//        log.info("userId: {}", result.getUserId());
//        log.info("userId: {}", userId);
//        log.info("userId.equals(result.getUserId()):{}", userId.equals(result.getUserId()));
//        log.info("userId == null:{}", userId != null);
        if(userId != null && userId.equals(result.getUserId())) {
            result.setLoginUser(true);
        }

        return result;
    }


    /**
     * 插入一篇博客
     * @param blogInfo
     * @param request
     * @return
     */
    @RequestMapping("insertBlog")
    public Result<?> insertBlog(BlogInfo blogInfo, HttpServletRequest request) {
        //校验参数
        if(blogInfo == null) {
            return Result.fail("参数为null");
        }
        if(!StringUtils.hasLength(blogInfo.getTitle())) {
            return Result.fail("标题不能为空");
        }
        if(!StringUtils.hasLength(blogInfo.getContent())) {
            return Result.fail("内容不能为空");
        }

        //获取用户id
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId = JwtUtils.getIdInToken(token);
        blogInfo.setUserId(userId);

        //log.info("接收到数据：{}", blogInfo);

        //插入数据
        Integer result = blogInfoService.insertBlog(blogInfo);

        //返回结果
        if(result.equals(1)) {
            return Result.success(true);
        }
        return Result.fail("未知错误");
    }

    /**
     * 更新博客内容
     * @param blogInfo
     * @return
     */
    @RequestMapping("/updateBlog")
    public Result<?> updateBlog(BlogInfo blogInfo) {
        //log.info("接收到数据：{}", blogInfo);
        if(blogInfo == null) {
            return Result.fail("博客信息为null");
        }
        if(!StringUtils.hasLength(blogInfo.getTitle())) {
            return Result.fail("标题不能为空");
        }
        if(!StringUtils.hasLength(blogInfo.getContent())) {
            return Result.fail("内容不能为空");
        }

        Integer result = blogInfoService.updateBlog(blogInfo);
        if(result == 1) {
            return Result.success(true);
        }
        return Result.fail("未知错误");
    }

    /**
     * 删除博客
     * @param blogId
     * @return
     */
    @RequestMapping("/deleteBlog")
    public Result<?> deleteBlog(Integer blogId) {
        //log.info("blogId:{}", blogId);
        if(blogId == null) {
            return Result.fail("blogId为null");
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);
        Integer result = blogInfoService.updateBlog(blogInfo);
        if(result == 1) {
            return Result.success(true);
        }
        return Result.fail("未知错误");
    }
}
